#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import logging
import os
import sys
import subprocess

class RunnerError(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)

class Runner:
    # TODO: logging needed
    def __init__(self):
        self.__default_env = {"preinstall" : "", "install": "", "postinstall" : "",
                            "preremove" : "", "remove" : "", "postremove" : ""}
        
        self.__default_env.update(os.environ)
        self.__logging = logging.getLogger("Runner")
        # SystemRoot variable is needed for subprocess.Popen working under Python 2.6
        # http://bugs.python.org/issue3440
        if "SystemRoot" in os.environ:
            self.__env = {"SystemRoot": os.environ["SystemRoot"]}
        else:
            self.__env = {}

    def prepare(self):
        self.__env.update(self.__default_env)

    def run(self, script, args):
        cur_path = os.getcwd()
        try:
            self.__logging.info("Executing script '%s'" % script.name)
            os.chdir(os.path.dirname(script.path))
            #look at http://docs.python.org/library/runpy.html to change if needed
            pargs = ["python", script.path];
            
            if args != None:
                pargs += args
            
            p = subprocess.Popen(pargs, env=self.__env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (std_out, std_err) = p.communicate()
            if len(std_out) > 0:
                self.__logging.info("Script '%s'" % script.name)
                output = std_out.strip("\r\n")
                self.__env[script.name] = output
                
            if len(std_err) > 0:
                self.__logging.debug(std_err)
                raise RunnerError(std_err)
        finally:
            os.chdir(cur_path)
